package com.clippick;

import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import co.kr.clippick.R;

import com.clippick.api.GetApi;
import com.clippick.common.GlobalValue;
import com.clippick.common.Toasts;
import com.clippick.common.Utils;

public class NewIntroActivity extends Activity {
	private Context mContext;

	private Button signupButton;
	private ProgressDialog mProgress = null;

	private ConnectivityManager manager;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_intro);

		mContext = this;

		manager = (ConnectivityManager) mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		Button loginButton = (Button) findViewById(R.id.login_button);
		loginButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(mContext, NewLoginActivity.class);
				startActivity(intent);
			}
		});

		signupButton = (Button) findViewById(R.id.signup_button);
		signupButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(mContext, NewJoinActivity.class);
				startActivity(intent);
			}
		});

		mProgress = new ProgressDialog(mContext);
		mProgress.setMessage("Loading...");

		if (Utils.checkNetwokState(manager)) {
			checkAutoLoginUser();
		} else {
			Toasts.showToast(mContext, getString(R.string.network_fail));
		}

		IntentFilter filterFinishIntro = new IntentFilter();
		filterFinishIntro.addAction("com.new.clippick.FinishIntro");
		registerReceiver(finishIntroActivityReceiver, filterFinishIntro);
	}

	public void onResume() {
		super.onResume();
		manager = (ConnectivityManager) mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
	}

	BroadcastReceiver finishIntroActivityReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Log.d("onReceive", "Logout in progress");
			finish();
		}
	};

	public void checkAutoLoginUser() {
		if (GlobalValue.isFbUser(mContext)
				&& !GlobalValue.getFacebookEmail(mContext).equals("")) {
			mProgress.show();
			new FacebookLoginTask().execute();

		} else if (!GlobalValue.getUserPassword(mContext).equals("")
				&& !GlobalValue.getUserEmail(mContext).equals("")) {
			mProgress.show();
			new LoginTask().execute();
		}
	}

	// HTTP Request from thread
	class LoginTask extends AsyncTask<String, String, String> {
		int returnCode = 0;
		String returnMessage = null;
		Map<String, String> response = null;

		@Override
		protected String doInBackground(String... params) {
			GetApi api = new GetApi(mContext);
			response = api.loginApi(GlobalValue.getUserEmail(mContext),
					GlobalValue.getUserPassword(mContext));
			returnCode = Integer.parseInt(response.get("returnCode"));

			if (returnCode != 200) {
				returnMessage = response.get("returnMessage");
			}

			return null;
		}

		protected void onPostExecute(String unused) {
			switch (returnCode) {
			case 200:
				// store as global variable to access easier
				Log.i("intro", response + "");
				GlobalValue.USER_ID = GlobalValue.getUserEmail(mContext);
				GlobalValue.USER_KEY = GlobalValue
						.getUserRegistrationKey(mContext);
				GlobalValue.UPDATE_TIME = response.get("UPDATE_TIME")
						.toString();
				GlobalValue.storeUserRegistrationKey(mContext,
						GlobalValue.USER_KEY);

				GlobalValue.AppLatestSyncTime = GlobalValue.UPDATE_TIME;

				Intent intent = new Intent(mContext, NewMainActivity.class);
				startActivity(intent);
				finish();
				break;

			default:
				break;
			}
		}
	}

	// HTTP Request from thread
	class FacebookLoginTask extends AsyncTask<String, String, String> {
		String returnMessage = null;

		@Override
		protected String doInBackground(String... params) {
			GetApi api = new GetApi(mContext);
			returnMessage = api.loginWithFacebook(
					GlobalValue.getFacebookUUID(mContext),
					GlobalValue.getFacebookEmail(mContext));

			return null;
		}

		protected void onPostExecute(String unused) {
			mProgress.dismiss();
			Log.i("fb_lg_task", "returnMessage" + returnMessage);
			try {
				JSONObject json = new JSONObject(returnMessage);
				int returnCode = Integer.parseInt(json.getString("returnCode"));

				switch (returnCode) {
				case 200:
					GlobalValue.USER_ID = GlobalValue
							.getFacebookEmail(mContext);
					GlobalValue.USER_KEY = json.getString("REGISTRATION_KEY");
					GlobalValue.AppLatestSyncTime = GlobalValue.UPDATE_TIME;
					GlobalValue.storeUserRegistrationKey(mContext,
							GlobalValue.USER_KEY);

					Intent intent = new Intent(mContext, NewMainActivity.class);
					startActivity(intent);
					finish();

					break;

				default:
					break;
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(finishIntroActivityReceiver);
	}
}